package com.tstudy.laoshibang.base;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.apache.http.Header;

import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.baidu.mapapi.search.core.CityInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.google.gson.Gson;
import com.tencent.mm.sdk.openapi.BaseReq;
import com.tencent.mm.sdk.openapi.BaseResp;
import com.tencent.mm.sdk.openapi.ConstantsAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.active.ActiveDetailFragment;
import com.tstudy.laoshibang.active.ActiveListFragment;
import com.tstudy.laoshibang.community.CommunityDetailFragment;
import com.tstudy.laoshibang.community.CommunityListFragment;
import com.tstudy.laoshibang.community.OfficialCommunityDetailFragment;
import com.tstudy.laoshibang.custom.CircleView;
import com.tstudy.laoshibang.event.GroupMessageEvent;
import com.tstudy.laoshibang.group.GroupProfileFragment;
import com.tstudy.laoshibang.group.GroupRecommendFragment;
import com.tstudy.laoshibang.group.MyGroupFragment;
import com.tstudy.laoshibang.login.LoginActivity;
import com.tstudy.laoshibang.login.RegistSuccessFragment;
import com.tstudy.laoshibang.manager.CityManager;
import com.tstudy.laoshibang.manager.CommunityMessageManager;
import com.tstudy.laoshibang.manager.DictionaryManager;
import com.tstudy.laoshibang.mode.CommunityMessage;
import com.tstudy.laoshibang.mode.TGroup;
import com.tstudy.laoshibang.mode.response.GroupDetailResponse;
import com.tstudy.laoshibang.mode.response.SelectGroupResponse;
import com.tstudy.laoshibang.profile.MessageDetailFragment;
import com.tstudy.laoshibang.profile.ProfileFragment;
import com.tstudy.laoshibang.share.WrapWechat;
import com.tstudy.laoshibang.utils.CommonUtil;
import com.tstudy.laoshibang.utils.LogUtil;
import com.tstudy.laoshibang.weike.WeikeDetailPlayerFragment;
import com.tstudy.laoshibang.weike.WeikeListFragment;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UpdateConfig;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import de.greenrobot.event.EventBus;

@SuppressLint({ "HandlerLeak", "InflateParams" })
@EActivity(R.layout.index)
public class IndexActivity extends BaseActivity implements IWXAPIEventHandler,OnGetPoiSearchResultListener, OnGetSuggestionResultListener{
	
	@ViewById(R.id.index_root)
	public RelativeLayout mRootLayout;
	
	@ViewById(R.id.index_fragment_root)
	public RelativeLayout mFragmentLayout;
	
	@ViewById(R.id.index_tab_layout)
	public LinearLayout mIndexTabLayout;
	
	@ViewById(R.id.index_tab_weike_layout)
	public RelativeLayout mTabWeikeLayout;
	
	@ViewById(R.id.index_tab_active_layout)
	public RelativeLayout mTabActiveLayout;
	
	@ViewById(R.id.index_tab_community_layout)
	public RelativeLayout mTabCommunityLayout;
	
	@ViewById(R.id.index_tab_profile_layout)
	public RelativeLayout mTabProfileLayout;
	
	@ViewById(R.id.index_tab_community_message_icon)
	public CircleView mNewMessageIcon;
	
	
	public static final int INDEX_TAB_ACTIVE = 0;
	public static final int INDEX_TAB_WEIKE = 1;
	public static final int INDEX_TAB_COMMUNITY = 2;
	public static final int INDEX_TAB_PROFILE = 3;
	
	public int mCurrentIndex = -1;
	public int mLastIndex = -1;
	boolean mIsFirstCreate;//是否第一次创建
	boolean mIsNewUser;
	LayoutInflater mInflater;
	Handler mHandler;
	int mTabIndex;
	boolean mIsLaunch;//是否启动
	boolean mShowMessage;
	private static Boolean isExit = false;  
	long mExitTime;
	long mPressTwiceTime;
	@ColorRes(R.color.theme_red)
	int selectTabTextColor;
	@ColorRes(R.color.text_color_black)
	int unSelectTabTextColor;
	Dialog mUpdateDialog;
	private LocationClient mLocationClient;
	private LocationMode tempMode = LocationMode.Hight_Accuracy;
	PoiSearch mPoiSearch;
	public static void show(boolean isNewUser){
		show(isNewUser,true,IndexActivity.INDEX_TAB_ACTIVE);
	}
	
	public static void messageShow(Context context,Bundle bundle){
		Intent intent = new Intent(BaseApplication.mContext,IndexActivity_.class);
		intent.putExtra(CONSTANT.ARGS.BUNDLE, bundle);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		if (context != null) {
			context.startActivity(intent);
		}
	}
	
	public static void show(boolean isNewUser,boolean isLaunch,int tabIndex){
		Intent intent = new Intent(BaseApplication.mContext,IndexActivity_.class);
		intent.putExtra(CONSTANT.ARGS.IS_NEW_USER, isNewUser);
		intent.putExtra(CONSTANT.ARGS.IS_LANUCH, isLaunch);
		intent.putExtra(CONSTANT.ARGS.TAB_INDEX, tabIndex);
		if (BaseApplication.mCurrentActivity != null) {
			BaseApplication.mCurrentActivity.startActivity(intent);
		}
	}
	
	public static void show(boolean isNewUser,boolean isLaunch){
		show(isNewUser, isLaunch, INDEX_TAB_ACTIVE);
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		EventBus.getDefault().register(this);
		if (!BaseApplication.checkGroup() ) {
			getGroupProfile(null);
		}
		mInflater = LayoutInflater.from(this);
		if (savedInstanceState == null) {
			mIsFirstCreate = true;
		}else{
			mIsFirstCreate = false;
		}
		LogUtil.d("channel value==" + CommonUtil.getChannelValue());
		new InitCityTask().execute();
		new InitDictionaryTask().execute();
		mLocationClient = ((BaseApplication)getApplication()).mLocationClient;
		initLocation();
		mLocationClient.start();
		UmengUpdateAgent.setUpdateOnlyWifi(false);
        UmengUpdateAgent.update(this);
        UpdateConfig.setDebug(true);
		WrapWechat.getInstance().registAppId(this);
		mHandler = new Handler();
	}
	
	 private class InitCityTask extends AsyncTask<Void, Void, Void> {
	        @Override
	        protected Void doInBackground(Void... params) {
	            CityManager.getInstance().initCityData();
	            return null;
	        }

	        @Override
	        protected void onPreExecute() {
	            super.onPreExecute();
	        }

	        @Override
	        protected void onPostExecute(Void aVoid) {
	            super.onPostExecute(aVoid);
	        }
	    }
	
	private class InitDictionaryTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
        	BaseApplication.checkLogin();//登录状态
        	DictionaryManager.getInstance().initDictionaryData();
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
        }
    }
	
	@Override
	protected void onStart() {
		super.onStart();
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putInt(CONSTANT.ARGS.CURRENT_INDEX, mCurrentIndex);
		LogUtil.d("--execute onSaveInstanceState:" + mCurrentIndex);
		super.onSaveInstanceState(outState);
	}
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		if (savedInstanceState != null) {
			mCurrentIndex = savedInstanceState.getInt(CONSTANT.ARGS.CURRENT_INDEX);
			changeTabBg(mCurrentIndex);
		}
		LogUtil.d("--execute onRestoreInstanceState:" + savedInstanceState + "," + mCurrentIndex);
		super.onRestoreInstanceState(savedInstanceState);
	}
	
//	public void initTitleBarHeight(){
//		mRootLayout.post(new Runnable() {
//			@Override
//			public void run() {
//				Rect rect = new Rect();
//				Window window = getWindow();
//				mRootLayout.getWindowVisibleDisplayFrame(rect);
//				int statusBarHeight = rect.top;
//				int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT).getTop();
//				int titleBarHeight = contentViewTop - statusBarHeight;
//			}
//		});
//		
//	}
	
	@AfterViews
	public void initView() {
		LogUtil.d("--initView execute:" + mCurrentIndex);
		mRootId = mRootLayout.getId();
		mRootFragmentId = mFragmentLayout.getId();
		if (mIsFirstCreate) {
			changeTabBg(INDEX_TAB_ACTIVE);
			ActiveListFragment.add(mRootId);
		}
		pushAction();
		gotoMessage();
	}
	
	public void pushAction(){
		List<CommunityMessage> communityMessageList  = CommunityMessageManager.getInstance().queryUnRead();
		if (communityMessageList != null && communityMessageList.size() > 0) {
			int size = communityMessageList.size();
			for (int i = 0; i < size; i++) {
				communityMessageList.get(i).parseObject();
			}
			showMessageIcon(communityMessageList.get(0).tcUreadNum);
		}
	}
	public void gotoMessage(){
		if (getIntent() != null) {
			Bundle bundle = getIntent().getBundleExtra(CONSTANT.ARGS.BUNDLE);
			if (bundle != null) {
				int mBussType = bundle.getInt(CONSTANT.ARGS.BUSS_TYPE, -1);
				int mAssoId = bundle.getInt(CONSTANT.ARGS.ASSO_ID, -1);
				String url = bundle.getString(CONSTANT.ARGS.URL);
				String groupId = bundle.getString(CONSTANT.ARGS.GROUP_ID);
				String groupName = bundle.getString(CONSTANT.ARGS.GROUP_NAME);
				String value = "";
				switch (mBussType) {
				case CONSTANT.PUSH_BUSINESS_TYPE_ACTIVE:
					value = BaseApplication.getResString(R.string.active_list_title);
					ActiveDetailFragment.add(((BaseActivity)BaseApplication.getTopActivity()).mRootId, mAssoId,-1,groupId);
					break;
				case CONSTANT.PUSH_BUSINESS_TYPE_SYSTEM:
					value = BaseApplication.getResString(R.string.message_list_title);
					MessageDetailFragment.add(((BaseActivity)BaseApplication.getTopActivity()).mRootId, mAssoId,0,url,null);
					break;
				case CONSTANT.PUSH_BUSINESS_TYPE_WEIKE:
					value = BaseApplication.getResString(R.string.weike_list_title);
					WeikeDetailPlayerFragment.add(((BaseActivity)BaseApplication.getTopActivity()).mRootId, mAssoId,-1,groupId);
					break;
				case CONSTANT.PUSH_BUSINESS_TYPE_GROUP_AGREE:
					value = CONSTANT.EVENT_VALUE.GROUP_AGREE;
					BaseApplication.changeGroupAction(new TGroup(groupId, groupName));
//					getGroupProfile(null);
					break;
				case CONSTANT.PUSH_BUSINESS_TYPE_GROUP_REJECT:
//					value = CONSTANT.EVENT_VALUE.GROUP_REJECT;
//					MessageDetailFragment.add(((BaseActivity)BaseApplication.getTopActivity()).mRootId, mAssoId,0,url,null);
					
					break;
				case CONSTANT.PUSH_BUSINESS_TYPE_GROUP_REMOVE:
					value = CONSTANT.EVENT_VALUE.GROUP_REMOVE;
					if (BaseApplication.mCurrentGroup != null && groupId != null && groupId.equals(BaseApplication.mCurrentGroup.groupId)) {
						getGroupProfile(null);;//被移出当前群组，默认回到官方群组
					}else{
						MessageDetailFragment.add(((BaseActivity)BaseApplication.getTopActivity()).mRootId, mAssoId,0,url,null);
					}
					break;
				case CONSTANT.PUSH_BUSINESS_TYPE_ADMIN:
					value = BaseApplication.getResString(R.string.message_admin_title);
					MessageDetailFragment.add(((BaseActivity)BaseApplication.getTopActivity()).mRootId, mAssoId,0,url,null);
					break;
				default:
					break;
				}
				CommonUtil.umengEvent(CONSTANT.EVENT_ID.PUSH_MESSAGE, "类型", value);
			}
		}
	}
	
	public void showMessageIcon(int count){
		if (count > 0 && mNewMessageIcon.getVisibility() == View.INVISIBLE) {
			mNewMessageIcon.setVisibility(View.VISIBLE);
		}
		if (count == 0 && mNewMessageIcon.getVisibility() == View.VISIBLE) {
			mNewMessageIcon.setVisibility(View.INVISIBLE);
		}
		mNewMessageIcon.setNotifiText(count);
		mNewMessageIcon.setBackgroundColor(BaseApplication.getResColor(R.color.theme_red));
	}
	
	@Click(R.id.index_tab_active_layout)
	public void gotoActive(){
		int tag = Integer.valueOf(mTabActiveLayout.getTag().toString());
		if (mCurrentIndex != tag) {
			ActiveListFragment.add(mRootId);
			changeTabBg(tag);
		}
	}
	
	@Click(R.id.index_tab_weike_layout)
	public void gotoWeike(){
		int tag = Integer.valueOf(mTabWeikeLayout.getTag().toString());
		if (mCurrentIndex != tag) {
			WeikeListFragment.add(mRootId);
			changeTabBg(tag);
		}
	}
	
	@Click(R.id.index_tab_community_layout)
	public void gotoCommunity(){
		int tag = Integer.valueOf(mTabCommunityLayout.getTag().toString());
		if(tag != mCurrentIndex){
			CommunityListFragment.add(mRootId);
		}
		changeTabBg(tag);
	}
	
	@Click(R.id.index_tab_profile_layout)
	public void gotoProfile(){
		int tag = Integer.valueOf(mTabProfileLayout.getTag().toString());
		if(tag != mCurrentIndex){
			ProfileFragment.add(mRootId);
		}
		changeTabBg(tag);
	}
	
	
	PopupWindow mPopUp;
	RelativeLayout mMyGroupLayout;
	TextView mGroupEmptyTxt;
	TextView mGroupEmptyUnderLine;
	RelativeLayout mGroupEmptyLayout;
	RelativeLayout mRecommendGroupLayout;
	TextView mOfficialIcon;
	TextView mMyGroupMore;
	TextView mRecommendMore;
	public List<TGroup> mJoinGroups = new ArrayList<TGroup>();
	public List<TGroup> mRecommendGroups = new ArrayList<TGroup>();
	public TGroup mOfficialGroup = new TGroup();
	public void showGroupPop() {
		if (mPopUp != null && mPopUp.isShowing()) {
			mPopUp.dismiss();
			return;
		}
		View groupLayout = mInflater.inflate(R.layout.group,null, false);
		mMyGroupLayout = (RelativeLayout) groupLayout.findViewById(R.id.group_my_group_layout);
		mGroupEmptyLayout = (RelativeLayout) groupLayout.findViewById(R.id.group_empty_layout);
		mGroupEmptyTxt = (TextView) groupLayout.findViewById(R.id.group_empty_txt);
		mGroupEmptyUnderLine = (TextView) groupLayout.findViewById(R.id.group_empty_under_line);
		mRecommendGroupLayout = (RelativeLayout) groupLayout.findViewById(R.id.group_recommend_layout);
		mOfficialIcon = (TextView) groupLayout.findViewById(R.id.group_official_value);
		mMyGroupMore = (TextView) groupLayout.findViewById(R.id.group_my_group_more);
		mRecommendMore = (TextView) groupLayout.findViewById(R.id.group_recommend_more);
		mMyGroupMore.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mPopUp.dismiss();
				mHandler.postDelayed(new Runnable() {
					@Override
					public void run() {
						if (BaseApplication.checkLogin()) {
							MyGroupFragment.add(mRootId);
						}else{
							LoginActivity.show();
						}
					}
				}, CONSTANT.POP_DELAY_TIME);
			}
		});
		mRecommendMore.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mPopUp.dismiss();
				mHandler.postDelayed(new Runnable() {
					@Override
					public void run() {
						GroupRecommendFragment.add(mRootId);
					}
				}, CONSTANT.POP_DELAY_TIME);
			}
		});
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				selectGroup();
			}
		}, CONSTANT.LOAD_DATA_DELAY_TIME);
		if (mPopUp == null) {
			initGroupPopup();
		}
		mPopUp.setContentView(groupLayout);
//		mPopUp.showAsDropDown(mFragmentLayout,0, 0);
		WindowManager.LayoutParams lp=getWindow().getAttributes();
        lp.alpha=0.5f;
        getWindow().setAttributes(lp);
		mPopUp.showAtLocation(mRootLayout,0, 0,BaseApplication.getResDimen(R.dimen.common_title_height) + BaseApplication.mStatusBarHeight);
	
	}
	int mGroupPopMargin = CommonUtil.dip2px(50);
	int titleHeight = BaseApplication.getResDimen(R.dimen.common_title_height);
	int mGroupPopWidth = BaseApplication.mScreenWidth - mGroupPopMargin;
	int mGroupPopHeight = BaseApplication.mScreenHeight-titleHeight-BaseApplication.mStatusBarHeight-mGroupPopMargin*2;
	public void initGroupPopup(){
		mPopUp = new PopupWindow(mGroupPopWidth,mGroupPopHeight);
		mPopUp.setAnimationStyle(R.style.AnimationFade);
		mPopUp.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);           
		mPopUp.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);  
		mPopUp.setFocusable(true);  
		mPopUp.setBackgroundDrawable(new ColorDrawable(0x00000000));
		mPopUp.setOutsideTouchable(true);
		mPopUp.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss() {
				WindowManager.LayoutParams lp=getWindow().getAttributes();
		        lp.alpha=1f;
		        getWindow().setAttributes(lp);
			}
		});
	}
	
	/**
	 * 选择群组
	 */
	private void selectGroup(){
		BaseJsonHandler<SelectGroupResponse> response = new BaseJsonHandler<SelectGroupResponse>() {
			public void onStart() {
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, SelectGroupResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					if (response.getData() != null) {
						if (response.getData().gf != null && response.getData().gf.size() > 0) {
							mOfficialGroup = response.getData().gf.get(0);
						}
						mRecommendGroups = response.getData().tjs;
						mJoinGroups = response.getData().joins;
						fillGroupLayout();
					}
				}else{
					BaseApplication.showToast(response.getErrMsg());
					afterLoading();
				}
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					SelectGroupResponse errorResponse) {
				afterLoading();
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected SelectGroupResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return new Gson().fromJson(rawJsonData,SelectGroupResponse.class);
			}
		};
		HttpManager.getInstance().selectGroup(BaseApplication.mUserNo, response);
	}
	
	public void fillGroupLayout(){
		mMyGroupLayout.removeAllViews();
		mRecommendGroupLayout.removeAllViews();
		if (mOfficialGroup != null) {
			mOfficialIcon.setText(mOfficialGroup.name);
			Drawable drawableOn= getResources().getDrawable(R.drawable.group_official_on);
			Drawable drawableOff= getResources().getDrawable(R.drawable.group_official_off);
			drawableOn.setBounds( 0 ,0 , drawableOn.getMinimumWidth(), drawableOn.getMinimumHeight());  
			drawableOff.setBounds( 0 ,0 , drawableOff.getMinimumWidth(), drawableOff.getMinimumHeight());  
			if (BaseApplication.mCurrentGroup != null && BaseApplication.mCurrentGroup.groupId.equals(mOfficialGroup.groupId)) {
				mOfficialIcon.setCompoundDrawables(null, null,drawableOn,null);
			}else{
				mOfficialIcon.setCompoundDrawables(null, null,drawableOff,null);
				mOfficialIcon.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						mPopUp.dismiss();
						BaseApplication.changeGroupAction(mOfficialGroup);
					}
				});
			}
		}
		if (BaseApplication.checkLogin()) {
			if (mJoinGroups != null && mJoinGroups.size() > 0) {
				mGroupEmptyLayout.setVisibility(View.GONE);
				mMyGroupLayout.setPadding(0, 0, 0, joinGroupMargin);
				fillJoinLayout(mMyGroupLayout);
			}else{
				int emptyViewWidth = BaseApplication.getResDimen(R.dimen.group_empty_view_width);
				int emptyViewMarginLeft = (mGroupPopWidth - emptyViewWidth)/2;
				mMyGroupLayout.setPadding(0, joinGroupMargin, 0, joinGroupMargin);
				RelativeLayout.LayoutParams imgLp = new RelativeLayout.LayoutParams(emptyViewWidth, RelativeLayout.LayoutParams.WRAP_CONTENT);
				imgLp.setMargins(emptyViewMarginLeft, 0, 0, 0);
				mGroupEmptyLayout.setVisibility(View.VISIBLE);
				mMyGroupLayout.addView(mGroupEmptyLayout,imgLp);
				mGroupEmptyTxt.setText(R.string.group_add_empty);
				mGroupEmptyLayout.setOnClickListener(null);
				mGroupEmptyUnderLine.setVisibility(View.GONE);
			}
		}else{
			int emptyViewWidth = BaseApplication.getResDimen(R.dimen.group_empty_view_width);
			int emptyViewMarginLeft = (mGroupPopWidth - emptyViewWidth)/2;
			mMyGroupLayout.setPadding(0, joinGroupMargin, 0, joinGroupMargin);
			RelativeLayout.LayoutParams imgLp = new RelativeLayout.LayoutParams(emptyViewWidth, RelativeLayout.LayoutParams.WRAP_CONTENT);
			imgLp.setMargins(emptyViewMarginLeft, 0, 0, 0);
			mGroupEmptyLayout.setVisibility(View.VISIBLE);
			mMyGroupLayout.addView(mGroupEmptyLayout,imgLp);
			mGroupEmptyTxt.setText("立即登录");
			mGroupEmptyUnderLine.setVisibility(View.VISIBLE);
			mGroupEmptyLayout.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					mPopUp.dismiss();
					mHandler.postDelayed(new Runnable() {
						@Override
						public void run() {
							LoginActivity.show();
						}
					}, CONSTANT.POP_DELAY_TIME);
					
				}
			});
		}
		
		if (mRecommendGroups != null && mRecommendGroups.size() > 0) {
			int size = mRecommendGroups.size();
			for (int i = 0; i < size; i++) {
				final TGroup group = mRecommendGroups.get(i);
				RelativeLayout layout = (RelativeLayout) mInflater.inflate(R.layout.recommend_group_item, null);
				ImageView image = (ImageView) layout.findViewById(R.id.recommend_group_item_image);
				TextView name = (TextView) layout.findViewById(R.id.recommend_group_item_name);
				TextView count = (TextView) layout.findViewById(R.id.recommend_group_item_member_count);
				ImageView addIcon = (ImageView) layout.findViewById(R.id.recommend_group_item_add_icon);
				HttpManager.getInstance().loadEditAvatar(image, group.imgIdxName,R.drawable.profile_avatar_default);
				name.setText(group.name);
				count.setText("(" + group.memberCn + ")");
				final int position = i;
				addIcon.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if (BaseApplication.checkLogin()) {
							groupApply(group,position);
						}else{
							mPopUp.dismiss();
							mHandler.postDelayed(new Runnable() {
								@Override
								public void run() {
									LoginActivity.show();
								}
							}, CONSTANT.POP_DELAY_TIME);
						}
					}
				});
				layout.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						mPopUp.dismiss();
						mHandler.postDelayed(new Runnable() {
							@Override
							public void run() {
								GroupProfileFragment.add(mRootId,group.groupId);
							}
						}, CONSTANT.POP_DELAY_TIME);
					}
				});
				layout.setId(i+1);
				RelativeLayout.LayoutParams layoutLp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
				layoutLp.addRule(RelativeLayout.BELOW,i);
				mRecommendGroupLayout.addView(layout,layoutLp);
			}
		}
	}
	boolean mIsLoading;
	private void groupApply(final TGroup group,final int position){
		if (mIsLoading) {
			return ;
		}
		mIsLoading = true;
		BaseJsonHandler<GroupDetailResponse> response = new BaseJsonHandler<GroupDetailResponse>() {
			public void onStart() {
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, GroupDetailResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					if (response.data != null) {
						switch (response.data.status.key) {
						case CONSTANT.GROUP_APPLY_ING:
							mRecommendGroups.get(position).status = response.data.status;
							RelativeLayout layout = (RelativeLayout)mRecommendGroupLayout.getChildAt(position);
							ImageView image = (ImageView) layout.getChildAt(3);
							image.setImageResource(R.drawable.group_btn_audit);
							break;
						case CONSTANT.GROUP_APPLY_SUCCESS:
							mPopUp.dismiss();
							BaseApplication.changeGroupAction(group);
							break;

						default:
							break;
						}
					}else{
						BaseApplication.showToast(response.getErrMsg());
					}
				}else {
					BaseApplication.showToast(response.getErrMsg());
				}
				afterLoading();
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					GroupDetailResponse errorResponse) {
				afterLoading();
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected GroupDetailResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return new Gson().fromJson(rawJsonData,GroupDetailResponse.class);
			}
		};
		HttpManager.getInstance().groupApply(BaseApplication.mUserNo, group.groupId, "", response);
	}
	
	public void afterLoading(){
		mIsLoading = false;
	}
	
	int joinGroupMargin = CommonUtil.dip2px(15);
	int joinGroupMarginTop = CommonUtil.dip2px(5);
	int imagePadding = CommonUtil.dip2px(10);
	int nameMarginTop = CommonUtil.dip2px(-5);
	int productImgWidth = (BaseApplication.mScreenWidth - joinGroupMargin*5 -imagePadding*9)/3;
	int iconWidth = CommonUtil.dip2px(16);
	int iconMargin = (productImgWidth-iconWidth)/2;
	public void fillJoinLayout(RelativeLayout layout){
		layout.removeAllViews();
		int size = mJoinGroups.size();
		for (int i = 0; i < size; i++) {
			final TGroup group = mJoinGroups.get(i);
			RelativeLayout.LayoutParams imgLp = new RelativeLayout.LayoutParams(productImgWidth, productImgWidth);
			RelativeLayout.LayoutParams iconLp = new RelativeLayout.LayoutParams(iconWidth,iconWidth);
			RelativeLayout.LayoutParams nameLp = new RelativeLayout.LayoutParams(productImgWidth, RelativeLayout.LayoutParams.WRAP_CONTENT);
			ImageView img = new ImageView(BaseApplication.mContext);
			ImageView icon = new ImageView(BaseApplication.mContext);
			TextView name = new TextView(BaseApplication.mContext);
			img.setId(i+1);
			name.setId(i+100);
			if (i > 0) {
				imgLp.addRule(RelativeLayout.RIGHT_OF,i);
			}
			nameLp.addRule(RelativeLayout.BELOW, img.getId());
			nameLp.addRule(RelativeLayout.ALIGN_LEFT, img.getId());
			nameLp.addRule(RelativeLayout.ALIGN_RIGHT, img.getId());
			if (i == 0) {
				imgLp.setMargins(joinGroupMargin,joinGroupMarginTop,0, 0);
			}else{
				imgLp.setMargins(joinGroupMargin, joinGroupMarginTop, 0, 0);
			}
			nameLp.setMargins(nameMarginTop*2, nameMarginTop, nameMarginTop*2, 0);
			name.setGravity(Gravity.CENTER);
			img.setScaleType(ScaleType.FIT_XY);
			img.setPadding(imagePadding, imagePadding, imagePadding, imagePadding);
//			img.setBackgroundColor(BaseApplication.getResColor(R.color.title_sp_line));
			HttpManager.getInstance().loadCommonImage(img, group.imgIdxName);
//			String url = CommonUtil.buildCropUrl(productImgWidth, productImgWidth);
//			HttpManager.getInstance().loadCornerImage(img, group.imgIdxName + url,CommonUtil.dip2px(3));
			name.setText(group.name);
			name.setEllipsize(TextUtils.TruncateAt.valueOf("END"));
			name.setSingleLine(true);
			if (BaseApplication.mCurrentGroup != null && group.groupId.equals(BaseApplication.mCurrentGroup.groupId)) {
				icon.setImageResource(R.drawable.group_official_on);
			}else{
				icon.setImageResource(R.drawable.group_official_off);
			}
			iconLp.addRule(RelativeLayout.ALIGN_LEFT,img.getId());
			iconLp.addRule(RelativeLayout.ALIGN_TOP,img.getId());
			iconLp.setMargins(iconMargin, iconMargin, 0, 0);
			layout.addView(img, imgLp);
			layout.addView(icon,iconLp);
			layout.addView(name, nameLp);
			img.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mPopUp.dismiss();
					BaseApplication.changeGroupAction(group);
				}
			});
		}
	}	
	/**
	 * 修改底部tab背景
	 * @param tag
	 */
	public void changeTabBg(int tag) {
		LogUtil.d("--changeTabBg==" + tag);
		if (mCurrentIndex != -1) {
			RelativeLayout lastTab = (RelativeLayout) mIndexTabLayout.getChildAt(mCurrentIndex);
//			lastTab.setBackgroundColor(0);
			lastTab.getChildAt(0).setSelected(false);
			if (mCurrentIndex == INDEX_TAB_PROFILE) {
				((TextView)lastTab.getChildAt(1)).setTextColor(unSelectTabTextColor);
			}else{
				((TextView)lastTab.getChildAt(1)).setTextColor(unSelectTabTextColor);
			}
		}
		RelativeLayout currentTab = (RelativeLayout) mIndexTabLayout.getChildAt(tag);
//		currentTab.setBackgroundColor(getResources().getColor(R.color.title_sp_line));
		currentTab.getChildAt(0).setSelected(true);
		if (tag == INDEX_TAB_PROFILE) {
			((TextView)currentTab.getChildAt(1)).setTextColor(selectTabTextColor);
		}else{
			((TextView)currentTab.getChildAt(1)).setTextColor(selectTabTextColor);
		}
		mCurrentIndex = tag;
	}
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if(mFragmentStack.size() > 0){
				if (mFragmentStack.get(mFragmentStack.size()-1) instanceof RegistSuccessFragment) {//注册成功后不允许返回
					BaseApplication.showToast(R.string.regist_success_nick_reqired);
				}else if (mFragmentStack.get(mFragmentStack.size()-1) instanceof CommunityDetailFragment) {//退出键盘及表情layout
					CommunityDetailFragment fragment = (CommunityDetailFragment)mFragmentStack.get(mFragmentStack.size()-1);
					if (fragment.isShowInput()) {
						fragment.clear();
					}else{
						remove(mRootId,mFragmentStack.get(mFragmentStack.size()-1));
					}
				}else if (mFragmentStack.get(mFragmentStack.size()-1) instanceof OfficialCommunityDetailFragment) {//退出键盘及表情layout
					OfficialCommunityDetailFragment fragment = (OfficialCommunityDetailFragment)mFragmentStack.get(mFragmentStack.size()-1);
					if (fragment.isShowInput()) {
						fragment.clear();
					}else{
						remove(mRootId,mFragmentStack.get(mFragmentStack.size()-1));
					}
				}else{
					remove(mRootId,mFragmentStack.get(mFragmentStack.size()-1));
				}
			}else{
				exitByDoubleClick();
			}
		}
		return false;
	}
//	@Override
//	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//		IspiedLog.d("--IndexActivity requestCode==" + requestCode + "--resultCode==" + resultCode);
//		WrapSinaWeibo.getInstance().activityResult(requestCode, resultCode, data);
//	}
	
	@Override
	public void initArgs() {
		mIsNewUser = getIntent().getBooleanExtra(CONSTANT.ARGS.IS_NEW_USER, false);
		mTabIndex = getIntent().getIntExtra(CONSTANT.ARGS.TAB_INDEX, 0);
		mIsLaunch = getIntent().getBooleanExtra(CONSTANT.ARGS.IS_LANUCH, false);
		mShowMessage = getIntent().getBooleanExtra(CONSTANT.ARGS.SHOW_MESSAGE, false);
		
	}
	@Override
	public void clear() {
		mTabCurrentFragment = null;
		mFragmentStack.clear();
		HttpManager.mCookiStore.clear();
//		XesApplication.currentLocation.isSetAddress = false;
	}
	
	@Override
	public void onReq(BaseReq req) {
		switch (req.getType()) {
		case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
//			goToGetMsg();		
			break;
		case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
//			goToShowMsg((ShowMessageFromWX.Req) req);
			break;
		default:
			break;
		}
	}

	@Override
	public void onResp(BaseResp resp) {
//		int result = 0;
//		LogUtil.d("-- wechat resp ==" + resp);
//		if (resp instanceof SendAuth.Resp) {
//			String code = ((SendAuth.Resp)resp).token;
//			LogUtil.d("--wechat resp code==" + code);
//			XesApplication.showToast("--wechat resp code ==" + code);
//		}
//		switch (resp.errCode) {
//		case BaseResp.ErrCode.ERR_OK:
//			result = R.string.errcode_success;
//			break;
//		case BaseResp.ErrCode.ERR_USER_CANCEL:
//			result = R.string.errcode_cancel;
//			break;
//		case BaseResp.ErrCode.ERR_AUTH_DENIED:
//			result = R.string.errcode_deny;
//			break;
//		default:
//			result = R.string.errcode_unknown;
//			break;
//		}
//		Toast.makeText(this, result, Toast.LENGTH_LONG).show();
	}
	
	private void getGroupProfile(String groupId){
		BaseJsonHandler<GroupDetailResponse> response = new BaseJsonHandler<GroupDetailResponse>() {
			public void onStart() {
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, GroupDetailResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					if (response.data != null) {
						BaseApplication.changeGroupAction(response.data);
					}
				}else {
                    BaseApplication.showToast(response.getErrMsg());
                }
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					GroupDetailResponse errorResponse) {
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected GroupDetailResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return new Gson().fromJson(rawJsonData,GroupDetailResponse.class);
			}
		};
		if (TextUtils.isEmpty(groupId)) {//获取官方群组
			HttpManager.getInstance().officialGroup(BaseApplication.mUserNo,response);
		}else{
			HttpManager.getInstance().getGroupDetail(BaseApplication.mUserNo, groupId, response);
		}
	}
	
	/**
	 * 连续点击返回键退出应用
	 */
	private void exitByDoubleClick() {  
	    Timer tExit = null;  
	    if (isExit == false) {  
	        isExit = true; // 准备退出  
	        BaseApplication.showToast(R.string.show_exit_desc);
	        tExit = new Timer();  
	        tExit.schedule(new TimerTask() {  
	            @Override  
	            public void run() {  
	                isExit = false; // 取消退出  
	            }  
	        }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务  
	  
	    } else {  
	        finish();  
	    }  
	}  
	private String tempcoor="gcj02";
	private void initLocation(){
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(tempMode);//设置定位模式
//		tempcoor="gcj02";
//		tempcoor="bd09";
		tempcoor="bd09ll";
		option.setCoorType(tempcoor);//返回的定位结果是百度经纬度，默认值gcj02  
		int span=50000;
		option.setScanSpan(span);//设置发起定位请求的间隔时间为5000ms
		option.setIsNeedAddress(true);
		mLocationClient.setLocOption(option);
	}
	
	public void onEventMainThread(Object object) {//更新消息数量显示
		if (object instanceof CommunityMessage) {
			pushAction();
		}if (object instanceof GroupMessageEvent) {
			if (mPopUp != null && mPopUp.isShowing()) {
				mPopUp.dismiss();
			}
		}
		
	}
	
	@Override
	protected void onDestroy() {
		mLocationClient.stop();
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	public void onGetPoiResult(PoiResult result) {
		if (result == null
				|| result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
			Toast.makeText(IndexActivity.this, "未找到结果", Toast.LENGTH_LONG)
			.show();
			return;
		}
		if (result.error == SearchResult.ERRORNO.NO_ERROR) {
//			mBaiduMap.clear();
//			PoiOverlay overlay = new MyPoiOverlay(mBaiduMap);
//			mBaiduMap.setOnMarkerClickListener(overlay);
//			overlay.setData(result);
//			overlay.addToMap();
//			overlay.zoomToSpan();
			return;
		}
		if (result.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) {

			// 当输入关键字在本市没有找到，但在其他城市找到时，返回包含该关键字信息的城市列表
			String strInfo = "在";
			for (CityInfo cityInfo : result.getSuggestCityList()) {
				strInfo += cityInfo.city;
				strInfo += ",";
			}
			strInfo += "找到结果";
			Toast.makeText(IndexActivity.this, strInfo, Toast.LENGTH_LONG)
					.show();
		}
	}

	public void onGetPoiDetailResult(PoiDetailResult result) {
		if (result.error != SearchResult.ERRORNO.NO_ERROR) {
			Toast.makeText(IndexActivity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT)
					.show();
		} else {
			Toast.makeText(IndexActivity.this, result.getName() + ": " + result.getAddress(), Toast.LENGTH_SHORT)
			.show();
		}
	}

	@Override
	public void onGetSuggestionResult(SuggestionResult res) {
		if (res == null || res.getAllSuggestions() == null) {
			return;
		}
//		sugAdapter.clear();
//		for (SuggestionResult.SuggestionInfo info : res.getAllSuggestions()) {
//			if (info.key != null)
//				sugAdapter.add(info.key);
//		}
//		sugAdapter.notifyDataSetChanged();
	}
}
